<template>
  <div class="study-profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>学习档案</span>
            </div>
          </template>

          <div class="profile-info">
            <div class="avatar-section">
              <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <img
                  v-if="profileData.avatar"
                  :src="`http://localhost:8080/api/users/avatar/${profileData.id}?t=${avatarTimestamp}`"
                  class="avatar"
                />
                <el-avatar
                  v-else
                  :size="100"
                  :src="defaultAvatar"
                >
                  {{ profileData.name }}
                </el-avatar>
                <div class="change-avatar-text">点击更换头像</div>
              </el-upload>
            </div>

            <div class="basic-info">
              <div class="info-item">
                <label>用户名:</label>
                <span>{{ profileData.username }}</span>
              </div>
              <div class="info-item">
                <label>姓名:</label>
                <span>{{ profileData.name }}</span>
              </div>
              <div class="info-item">
                <label>昵称:</label>
                <span>{{ profileData.nickname || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>性别:</label>
                <span>{{ getGenderText(profileData.gender) }}</span>
              </div>
              <div class="info-item">
                <label>出生日期:</label>
                <span>{{ profileData.birthDate ? formatDate(profileData.birthDate) : '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>学习积分:</label>
                <span class="points">{{ profileData.studyPoints || 0 }}</span>
              </div>
              <div class="info-item">
                <label>学习等级:</label>
                <span>Lv.{{ profileData.studyLevel || 1 }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 学习统计 -->
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>学习统计</span>
            </div>
          </template>

          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ stats.enrolledCourses }}</div>
              <div class="stat-label">报名课程</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.completedCourses }}</div>
              <div class="stat-label">完成课程</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.completedLessons }}</div>
              <div class="stat-label">完成课时</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.questionsAsked }}</div>
              <div class="stat-label">我的提问</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.answersGiven }}</div>
              <div class="stat-label">我的回答</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.acceptedAnswers }}</div>
              <div class="stat-label">获赞回答</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑和成就 -->
      <el-col :span="16">
        <el-tabs v-model="activeTab" type="card">
          <!-- 基本信息编辑 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>编辑基本信息</span>
                </div>
              </template>

              <el-form
                :model="basicInfoForm"
                :rules="basicInfoRules"
                ref="basicInfoFormRef"
                label-width="100px"
              >
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="basicInfoForm.name" />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="basicInfoForm.nickname" />
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="basicInfoForm.phone" />
                </el-form-item>
                <el-form-item label="部门" prop="department">
                  <el-input v-model="basicInfoForm.department" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="basicInfoForm.gender" placeholder="请选择性别">
                    <el-option label="男" value="MALE" />
                    <el-option label="女" value="FEMALE" />
                    <el-option label="保密" value="OTHER" />
                  </el-select>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthDate">
                  <el-date-picker
                    v-model="basicInfoForm.birthDate"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item label="个人简介" prop="bio">
                  <el-input
                    v-model="basicInfoForm.bio"
                    type="textarea"
                    :rows="4"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateBasicInfo">保存信息</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>

          <!-- 我的成就 -->
          <el-tab-pane label="我的成就" name="achievements">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>我的成就</span>
                </div>
              </template>

              <div class="achievements-grid">
                <div
                  v-for="achievement in achievements"
                  :key="achievement.id"
                  class="achievement-item"
                >
                  <div class="achievement-icon">
                    <el-icon v-if="achievement.badgeIcon"><Trophy /></el-icon>
                    <el-avatar
                      v-else
                      :size="60"
                      :icon="Trophy"
                    />
                  </div>
                  <div class="achievement-info">
                    <h4>{{ achievement.achievementName }}</h4>
                    <p>{{ achievement.description }}</p>
                    <div class="achievement-meta">
                      <span class="achievement-type">{{ achievement.achievementType }}</span>
                      <span class="achievement-date">{{ formatDate(achievement.earnedTime) }}</span>
                    </div>
                  </div>
                </div>

                <div v-if="achievements.length === 0" class="no-achievements">
                  <el-icon><Trophy /></el-icon>
                  <p>暂无成就</p>
                </div>
              </div>
            </el-card>
          </el-tab-pane>

          <!-- 积分记录 -->
          <el-tab-pane label="积分记录" name="points">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>积分记录</span>
                  <div class="points-summary">
                    <span>当前积分: <strong>{{ profileData.studyPoints || 0 }}</strong></span>
                  </div>
                </div>
              </template>

              <el-table
                :data="pointsTransactions"
                style="width: 100%"
                stripe
              >
                <el-table-column
                  prop="transactionTime"
                  label="时间"
                  width="180"
                >
                  <template #default="scope">
                    {{ formatDate(scope.row.transactionTime) }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="description"
                  label="说明"
                />
                <el-table-column
                  prop="points"
                  label="积分"
                  width="100"
                  align="center"
                >
                  <template #default="scope">
                    <span :class="scope.row.points > 0 ? 'points-positive' : 'points-negative'">
                      {{ scope.row.points > 0 ? '+' : '' }}{{ scope.row.points }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>

              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="pointsPage"
                  v-model:page-size="pointsPageSize"
                  :page-sizes="[10, 20, 50]"
                  :total="totalPointsTransactions"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handlePointsSizeChange"
                  @current-change="handlePointsCurrentChange"
                />
              </div>
            </el-card>
          </el-tab-pane>

          <!-- 我的学习 -->
          <el-tab-pane label="我的学习" name="learning">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>我的学习</span>
                </div>
              </template>

              <el-table
                :data="enrollments"
                style="width: 100%"
                stripe
              >
                <el-table-column
                  prop="courseTitle"
                  label="课程名称"
                />
                <el-table-column
                  prop="enrollmentStatus"
                  label="状态"
                  width="120"
                >
                  <template #default="scope">
                    <el-tag
                      :type="getEnrollmentStatusType(scope.row.enrollmentStatus)"
                    >
                      {{ getEnrollmentStatusText(scope.row.enrollmentStatus) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="progressPercentage"
                  label="进度"
                  width="150"
                >
                  <template #default="scope">
                    <el-progress
                      :percentage="scope.row.progressPercentage || 0"
                      :show-text="true"
                      :stroke-width="10"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="enrollmentDate"
                  label="报名时间"
                  width="180"
                >
                  <template #default="scope">
                    {{ formatDate(scope.row.enrollmentDate) }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="120"
                >
                  <template #default="scope">
                    <el-button
                      v-if="scope.row.enrollmentStatus === 'ENROLLED' || scope.row.enrollmentStatus === 'IN_PROGRESS'"
                      type="primary"
                      size="small"
                      @click="continueLearning(scope.row.courseId)"
                    >
                      继续学习
                    </el-button>
                    <el-button
                      v-else-if="scope.row.enrollmentStatus === 'COMPLETED'"
                      type="success"
                      size="small"
                      disabled
                    >
                      已完成
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="enrollmentsPage"
                  v-model:page-size="enrollmentsPageSize"
                  :page-sizes="[10, 20, 50]"
                  :total="totalEnrollments"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleEnrollmentsSizeChange"
                  @current-change="handleEnrollmentsCurrentChange"
                />
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Trophy
} from '@element-plus/icons-vue'
import request from '../../utils/request'
import { hasRole } from '../../utils/auth'
import defaultAvatar from '../../assets/images/default-avatar.png'

// 路由
const router = useRouter()

// 当前激活的标签页
const activeTab = ref('basic')

// 数据
const profileData = ref({
  id: 0,
  username: '',
  name: '',
  phone: '',
  department: '',
  role: '',
  status: 1,
  avatar: '',
  nickname: '',
  gender: '',
  birthDate: '',
  bio: '',
  studyPoints: 0,
  studyLevel: 1
})

// 头像时间戳，用于避免缓存
const avatarTimestamp = ref(Date.now())

// 基本信息表单
const basicInfoForm = reactive({
  name: '',
  nickname: '',
  phone: '',
  department: '',
  gender: '',
  birthDate: '',
  bio: ''
})

// 基本信息表单验证规则
const basicInfoRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
}

// 表单引用
const basicInfoFormRef = ref()

// 学习统计数据
const stats = ref({
  enrolledCourses: 0,
  completedCourses: 0,
  completedLessons: 0,
  questionsAsked: 0,
  answersGiven: 0,
  acceptedAnswers: 0
})

// 成就数据
const achievements = ref([])

// 积分交易记录
const pointsTransactions = ref([])
const pointsPage = ref(1)
const pointsPageSize = ref(10)
const totalPointsTransactions = ref(0)

// 我的学习记录
const enrollments = ref([])
const enrollmentsPage = ref(1)
const enrollmentsPageSize = ref(10)
const totalEnrollments = ref(0)

// 获取用户学习档案
const fetchUserProfile = async () => {
  try {
    const response = await request.get('/api/study/profile')
    profileData.value = {
      ...profileData.value,
      ...response.data
    }

    // 更新表单数据
    basicInfoForm.name = profileData.value.name
    basicInfoForm.nickname = profileData.value.nickname || ''
    basicInfoForm.phone = profileData.value.phone || ''
    basicInfoForm.department = profileData.value.department || ''
    basicInfoForm.gender = profileData.value.gender || ''
    basicInfoForm.birthDate = profileData.value.birthDate ?
      new Date(profileData.value.birthDate).toISOString().split('T')[0] : ''
    basicInfoForm.bio = profileData.value.bio || ''
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 获取学习统计数据
const fetchStudyStats = async () => {
  try {
    // 获取报名课程数量和已完成课程数量
    const enrollmentsResponse = await request.get('/api/study/courses/enrollments/all')
    
    // 从返回的数据中筛选不同状态的报名
    if (enrollmentsResponse.data && enrollmentsResponse.data.content) {
      const enrollments = enrollmentsResponse.data.content
      stats.value.enrolledCourses = enrollments.filter(e => e.status === 'PENDING').length
      stats.value.completedCourses = enrollments.filter(e => e.status === 'APPROVED').length
    }

    // 获取积分总数
    const pointsResponse = await request.get('/api/study/points/total')
    profileData.value.studyPoints = pointsResponse.data

    // 获取成就数量
    const achievementsResponse = await request.get('/api/study/achievements')
    achievements.value = achievementsResponse.data

    // 获取问题和回答统计
    const questionsResponse = await request.get('/api/study/questions', {
      params: {
        userId: profileData.value.id
      }
    })
    stats.value.questionsAsked = questionsResponse.data.totalElements

    const answersResponse = await request.get('/api/study/questions/answers', {
      params: {
        userId: profileData.value.id
      }
    })
    stats.value.answersGiven = answersResponse.data.totalElements

    // 获取被采纳的回答数量（需要后端支持）
    // 暂时设置为0
    stats.value.acceptedAnswers = 0
  } catch (error) {
    console.error('获取学习统计数据失败:', error)
    ElMessage.error('获取学习统计数据失败')
  }
}

// 获取积分交易记录
const fetchPointsTransactions = async () => {
  try {
    const response = await request.get('/api/study/points', {
      params: {
        page: pointsPage.value - 1,
        size: pointsPageSize.value
      }
    })
    pointsTransactions.value = response.data.content
    totalPointsTransactions.value = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取积分记录失败')
  }
}

// 获取我的学习记录
const fetchEnrollments = async () => {
  try {
    const response = await request.get('/api/study/courses/enrollments/all')
    if (response.data && response.data.content) {
      enrollments.value = response.data.content
      totalEnrollments.value = response.data.content.length
    }
  } catch (error) {
    console.error('获取我的学习记录失败:', error)
    ElMessage.error('获取我的学习记录失败')
  }
}


// 头像上传前的检查
const beforeAvatarUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt6M = file.size / 1024 / 1024 < 6

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt6M) {
    ElMessage.error(`头像图片大小不能超过 6MB，当前文件大小: ${(file.size / 1024 / 1024).toFixed(2)}MB!`)
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options: any) => {
  const { file } = options
  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('avatar', file)

    // 上传头像文件
    const response = await request.post('/api/users/current/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    // 更新本地数据
    profileData.value.avatar = response.data.avatar
    // 更新头像时间戳以刷新显示
    avatarTimestamp.value = Date.now()
    ElMessage.success('头像上传成功')

    // 更新localStorage中的用户信息，确保右上角头像更新
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        userInfo.avatar = response.data.avatar
        localStorage.setItem('userInfo', JSON.stringify(userInfo))

        // 触发storage事件，通知其他组件更新头像
        window.dispatchEvent(new StorageEvent('storage', {
          key: 'userInfo',
          oldValue: userInfoStr,
          newValue: JSON.stringify(userInfo)
        }))
      } catch (parseError) {
        console.error('Error parsing or updating user info:', parseError)
        ElMessage.error('头像信息更新失败')
      }
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      ElMessage.error('文件上传超时，请选择较小的文件')
    } else if (error.message.includes('exceed')) {
      ElMessage.error('文件大小超过服务器限制，最大允许上传10MB的文件')
    } else {
      ElMessage.error('头像上传失败')
    }
  }
}

// 更新基本信息
const updateBasicInfo = async () => {
  if (!basicInfoFormRef.value) return

  await basicInfoFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 构造更新数据
        const updateData = {
          ...basicInfoForm,
          avatar: profileData.value.avatar
        }

        // 更新学习档案
        await request.put('/api/study/profile', updateData)

        ElMessage.success('信息更新成功')
        fetchUserProfile() // 重新获取用户信息
      } catch (error) {
        ElMessage.error('信息更新失败')
      }
    }
  })
}

// 继续学习
const continueLearning = (courseId: number) => {
  router.push(`/study/learning/${courseId}`)
}

// 工具方法
const getGenderText = (gender: string) => {
  switch (gender) {
    case 'MALE':
      return '男'
    case 'FEMALE':
      return '女'
    case 'OTHER':
      return '保密'
    default:
      return '未设置'
  }
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const getEnrollmentStatusType = (status: string) => {
  switch (status) {
    case 'ENROLLED':
      return 'info'
    case 'IN_PROGRESS':
      return 'warning'
    case 'COMPLETED':
      return 'success'
    default:
      return 'info'
  }
}

const getEnrollmentStatusText = (status: string) => {
  switch (status) {
    case 'ENROLLED':
      return '已报名'
    case 'IN_PROGRESS':
      return '学习中'
    case 'COMPLETED':
      return '已完成'
    default:
      return '未知'
  }
}

// 分页相关方法
const handlePointsSizeChange = (val: number) => {
  pointsPageSize.value = val
  pointsPage.value = 1
  fetchPointsTransactions()
}

const handlePointsCurrentChange = (val: number) => {
  pointsPage.value = val
  fetchPointsTransactions()
}

const handleEnrollmentsSizeChange = (val: number) => {
  enrollmentsPageSize.value = val
  enrollmentsPage.value = 1
  fetchEnrollments()
}

const handleEnrollmentsCurrentChange = (val: number) => {
  enrollmentsPage.value = val
  fetchEnrollments()
}

// 组件挂载时获取数据
onMounted(() => {
  // 检查用户角色，管理员和讲师不需要学习档案
  if (hasRole('ADMIN') || hasRole('LECTURER')) {
    ElMessage.error('管理员和讲师无需访问学习档案')
    router.push('/')
    return
  }
  
  fetchUserProfile()
  fetchStudyStats()
  fetchPointsTransactions()
  fetchEnrollments()
})
</script>

<style scoped>
.study-profile-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.profile-card {
  margin-bottom: 20px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  display: inline-block;
  cursor: pointer;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.change-avatar-text {
  margin-top: 10px;
  color: #409eff;
  font-size: 14px;
}

.basic-info .info-item {
  display: flex;
  margin-bottom: 15px;
}

.basic-info .info-item label {
  width: 80px;
  color: #606266;
  font-weight: bold;
}

.basic-info .info-item span {
  flex: 1;
  color: #303133;
}

.basic-info .info-item .points {
  color: #e6a23c;
  font-weight: bold;
  font-size: 18px;
}

.stats-card {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background-color: #f0f2f5;
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.achievements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.achievement-item {
  display: flex;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.achievement-icon {
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.achievement-icon .el-icon {
  font-size: 40px;
  color: #ffd700;
}

.achievement-info {
  flex: 1;
}

.achievement-info h4 {
  margin: 0 0 5px 0;
  color: #303133;
}

.achievement-info p {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.achievement-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.no-achievements {
  text-align: center;
  padding: 50px 0;
  color: #909399;
  grid-column: 1 / -1;
}

.no-achievements .el-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.points-summary {
  font-size: 16px;
  color: #303133;
}

.points-summary strong {
  color: #e6a23c;
  font-size: 18px;
}

.points-positive {
  color: #67c23a;
  font-weight: bold;
}

.points-negative {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
